package BIO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * TCP 协议Socket 使用BIO 进行通信： 服务器
 */
public class BIOServer {

    public static void main(String[] args) {
        // 使用socket 进行网络通信
        ServerSocket serverSocket = null;
        Socket socket = null;
        // 基于字节流
        InputStream in = null;
        OutputStream out = null;
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功， 监听端口为8000， 等待客户端连接");
            while (true) {
                socket = serverSocket.accept();
                System.out.println("客户端连接成功，客户信息为" + serverSocket.getInetAddress());
                in = socket.getInputStream();
                // TimeUnit.SECONDS.sleep(10);
                byte[] buffer = new byte[1024];
                int len = 0;
                // 读取客户端的数据
                while ((len = in.read(buffer)) > 0) {
                    System.out.println(new String(buffer, 0, len));
                }
                // 向客户端写数据
                out = socket.getOutputStream();
                out.write("hello!".getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}